//
//  StatusCell.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/7/1.
//  Copyright © 2015年 HeiMa. All rights reserved.
//(

import UIKit
import FFAutoLayout
import SDWebImage

/// 转发微博 cell
let HMStatusForwardCellIdentifier = "HMStatusForwardCellIdentifier"
/// 原创微博 cell
let HMStatusNormalCellIdentifier = "HMStatusNormalCellIdentifier"


/// 图片视图可重用标示符
private let HMPictureCellReuseIdentifier = "HMPictureCellReuseIdentifier"

class StatusCell: UITableViewCell,UICollectionViewDataSource {
    
    var forwardLabel: UILabel?
    
    var status: Status? {
        didSet {
            /// 转发文字
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ":" + (status?.retweeted_status?.text ?? "")
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            vipIconView.image = status?.user?.verifiedImage
            memberIconView.image = status?.user?.mbImage
            
            
            nameLable.text = status?.user?.name
            sourceLable.text = "刚刚"
            timeLable.text = "来自 微博"
            contentLable.text = status?.text
            
            let result = calcPictureViewSize(status!)
            widthCons?.constant = result.viewSize.width
            heightCons?.constant = result.viewSize.height
        
            pictureLayout.itemSize = result.itemSize
            
            pictureView.reloadData()
        }
    }
    
    class func cellIdentifier(status: Status) -> String {
        return status.retweeted_status != nil ? HMStatusForwardCellIdentifier : HMStatusNormalCellIdentifier
    }
    
    func recordPictureViewCons(cons: [NSLayoutConstraint]){
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    private func calcPictureViewSize(status: Status) ->(viewSize: CGSize, itemSize: CGSize) {
        // 获取数量 
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        let count = status.picURLs?.count ?? 0
        
        // 无图
        if count == 0 {
            return (CGSizeZero, itemSize)
        }
        
        // 单图
        if count == 1 {
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            return (image.size, image.size)
        }
        
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w), itemSize)
        }
        
        // 每行图片数量
        let rowCount = 3
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row-1) * margin
        
        return (CGSize(width: w, height: h),itemSize)
        
    }
    
    func rowHeight(status: Status) -> CGFloat {
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictreCell
        cell.imageURL = status?.picURLs![indexPath.item]
        return cell
    }
    
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let screenWidth = UIScreen.mainScreen().bounds.width
        
        // 顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        
        
        addSubview(iconView)
        addSubview(nameLable)
        addSubview(vipIconView)
        addSubview(timeLable)
        addSubview(memberIconView)
        addSubview(sourceLable)
        addSubview(contentLable)
        contentLable.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 18
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        preparePictureView()
        
//        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: <#T##CGSize?#>)
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 12))
        nameLable.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size:nil,offset: CGPoint(x: 8, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLable, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLable.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLable.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLable, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLable.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        // 配图视图
//        let cons = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLable, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
//         //记录宽高约束
//        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
//        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
        
        // 页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))

        
        iconView.image = UIImage(named: "new_feature_3")
    }
    
    private func preparePictureView() {
        pictureView.backgroundColor = UIColor.whiteColor()
        pictureView.dataSource = self
        pictureView.registerClass(StatusPictreCell.self, forCellWithReuseIdentifier: HMPictureCellReuseIdentifier)
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView = UIImageView()
    lazy var nameLable = UILabel(color: UIColor.darkGrayColor(), fontsize: 14)
    lazy var memberIconView : UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var timeLable = UILabel(color: UIColor.orangeColor(), fontsize: 10)
    lazy var sourceLable = UILabel(color: UIColor.darkGrayColor(), fontsize: 10)
    lazy var contentLable = UILabel(color: UIColor.darkGrayColor(), fontsize: 15, mutiLines: true)
    
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    
    
    lazy var footerView: StatusFooterView = StatusFooterView()
    
    // 配图视图的约束
    private var topCons: NSLayoutConstraint?
    private var widthCons: NSLayoutConstraint?
    private var heightCons: NSLayoutConstraint?
}

private class StatusPictreCell: UICollectionViewCell {
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL)
//            addSubview(iconView)
//            iconView.ff_Fill(self)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        addSubview(iconView)
        iconView.ff_Fill(self)
    }
    

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var iconView = UIImageView()
}

class StatusFooterView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn : UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commentBtn : UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
     lazy var likeBtn : UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)
    
}


